package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class MyTask {
    @Autowired
    private OrderMapper orderMapper;

    //    @Scheduled(cron = "0/5 * * * * ?")
    public void executeTask() {
        log.info("定时任务开始执行:{}", new Date());
    }

    /**
     * 每分钟自动将未支付的订单转化为取消订单
     */
//    @Scheduled(cron = "0 * * * * ?")
    public void executeTask4UnPaid() {
        log.info("自动将待付款且超时的订单转化为取消订单{}",LocalDateTime.now());
        Orders orders = new Orders();
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        //设置ordertime为失效时间
        orders.setOrderTime(LocalDateTime.now().minusMinutes(15));
        List<Orders> ordersList = orderMapper.getByOrders(orders);

        if (ordersList != null && ordersList.size() > 0) {
            List<Long> list = ordersList.stream().map(Orders::getId).collect(Collectors.toList());
//            批量修改订单状态为已取消
            orderMapper.updateStatus2CanCelBatch(list);

        }

    }


    /**
     * 每天凌晨1点自动将派送中的订单转化成已完成
     */
//    @Scheduled(cron = "0 0 1 * * ?")
    public void executeTask4DeliveryInProgress() {
        log.info("自动将派送中的订单转化为已完成{}",LocalDateTime.now());
        Orders orders = new Orders();
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orders.setOrderTime(LocalDateTime.now().minusHours(1));
        List<Orders> ordersList = orderMapper.getByOrders(orders);

        if (ordersList != null && ordersList.size() > 0) {
            List<Long> list = ordersList.stream().map(Orders::getId).collect(Collectors.toList());
            //批量修改订单状态为已完成
            orderMapper.updateStatus2CompleteBatch(list);


        }
    }
}